﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RiaCrm.Infrastructure;
using Acando.Dynamics.CRM.Silverlight.Library.Interfaces;
using Acando.Dynamics.CRM.Silverlight.Library.Model;
using Acando.Dynamics.CRM.Silverlight.Library.CrmSdk;
using System.Xml.Linq;
using System.Linq;
using System.ComponentModel;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Commands;
using Acando.Dynamics.CRM.Silverlight.Library.Helper;
using Acando.Dynamics.CRM.Silverlight.Library.Dialogs;

namespace RiaCrm.Sitemap
{
    public class SitemapViewModel : INotifyPropertyChanged
    {
        public String Organame { get; private set; }
        public IMetaDataLayer Metadatalayer { get; internal set; }

        public ICommand TreeNodeSelectedCommand { get; private set; }
        
        private IDataModel _datamodel;
        private String _sitemapAsXml;
        private IEventAggregator _eventAggregator;
        private String _storedFileName;
        private String _storedDirName;
        

        public String SitemapAsXml
        {
            get
            {
                return this._sitemapAsXml;
            }
            set
            {
                this._sitemapAsXml = value;
                this.OnPropertyChanged("SitemapAsXml");
            }
        }

        /* Constructor */
        public SitemapViewModel(IEventAggregator eventAggregator, InitParaOrgaName organame, IMetaDataLayer metadatalayer)
        {
            this.Organame = organame.Value;
            this.Metadatalayer = metadatalayer;
            this._datamodel = new DynamicDataModel("organization", this.Organame);
            this._eventAggregator = eventAggregator;
            //this.TreeNodeSelectedCommand = new DelegateCommand<string>(c => this._eventAggregator.GetEvent<StatedEntityChanged>().Publish(c.ToLower()));
            this.TreeNodeSelectedCommand = new DelegateCommand<String>(OnTreeNodeSelected);
            this._storedFileName = String.Format("{0}-{1}", "sitemap.xml", this.Organame);
            this._storedDirName = "sitemapXML";
            this.checkForAdequateIsolationStore();
        }

        /// <summary>
        /// In case the isolated storage space is not adequate, a warning dialog is shown
        /// </summary>
        private void checkForAdequateIsolationStore()
        {
            IncreaseStorageDialog dialog = null;

            var factor = 1060000;

            var targetSpace = (long)(10 * factor);

            if (IsolatedStoreHelper.CurrentSpaceIsLessThan(targetSpace))
            {
                dialog = new IncreaseStorageDialog(targetSpace);
                dialog.ShowDialog();
            }
        }

        public void LoadSiteMap()
        {
            if (IsolatedStoreHelper.FileExists(this._storedDirName, this._storedFileName))
            {
                this.SitemapAsXml = IsolatedStoreHelper.GetDataFromStore(this._storedDirName, this._storedFileName);
            }
            else
            {
                this._datamodel.RetrieveMultipleCompleted += new EventHandler<RetrieveMultipleCompletedEventArgs>(RetrieveCallback);
                this._datamodel.RetrieveMultiple();
            }
        
        }

        private void OnTreeNodeSelected(String nodeName)
        {
            // trigger event:
            this._eventAggregator.GetEvent<StatedEntityChanged>().Publish(nodeName.ToLower());
        }

        private void RetrieveCallback(object sender, RetrieveMultipleCompletedEventArgs e)
        {
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);
            else
            {
                DynamicEntity dynamicEntity = e.Result.BusinessEntities[0] as DynamicEntity;
                this.SitemapAsXml = dynamicEntity["sitemapxml"].ToString();

                // Store sitemapXML in isolated storage:
                IsolatedStoreHelper.StoreData(this._storedDirName, this._storedFileName, this.SitemapAsXml);
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion
    }
}
